#include "bitmap.h"
#include "file.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <vector>

using std::vector;

int main(int args,char** argv){

    printf("Nom du fichier d'animation?\n");
    char fname[1024];
    scanf("%s",fname);
    char stackfname[1030];
    sprintf(stackfname,"%s.csv",fname);
    printf("Lecture de %s...",stackfname);
    file csv(stackfname);
    if( !csv.opened() ){
        printf("erreur\n%s introuvable\n",stackfname);
        return EXIT_FAILURE;
    }

    vector<unsigned short>  delays;
    vector<bitmap*>         frames;
    unsigned short stack;
    csv.fscanf("%*s\n");
    int i = 0;
    printf("\n");
    anm_header hdr;
    while( !csv.eof() ){
        csv.fscanf("\"%hu\"\n",&stack);
        delays.push_back(stack);
        sprintf(stackfname,"%s%.4d.bmp",fname,i);
        frames.push_back(new bitmap(stackfname));
        if( i ){
            if( hdr.anm_bpp != frames.back()->getBpp() ){
                printf("Error: pixel format not constant, aborting\n");
                return EXIT_FAILURE;
            }
            if( hdr.anm_height != frames.back()->getHeight() ||
                hdr.anm_width != frames.back()->getWidth() ){
                printf("Error: bitmap sizes not constant, aborting\n");
                return EXIT_FAILURE;
            }
        }
        else{
            strncpy((char*)&hdr.anm_str,"ANM",3);
            hdr.anm_width = frames.front()->getWidth();
            hdr.anm_height = frames.front()->getHeight();
            hdr.anm_bpp = frames.front()->getBpp();
        }
        i++;
    }
    hdr.anm_frame_num = delays.size();

    sprintf(stackfname,"%s.anm",fname);
    file outfile( stackfname, "wb" );
    outfile.write(&hdr,sizeof(anm_header),1);
    for( vector<unsigned short>::iterator it = delays.begin(); it < delays.end(); it++ ){
        outfile.write(&(*it),sizeof(unsigned short),1);}
    for( vector<bitmap*>::iterator it = frames.begin(); it < frames.end(); it++ ){
        outfile.write((*it)->Data(),1, hdr.anm_width*hdr.anm_height*hdr.anm_bpp/8);}

    printf("Termine.\n");

};
